package com.soloyogame.anitoys.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;

import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class XstreamDateConverter implements Converter 
{
	
	public String format; 
	public XstreamDateConverter(String format){
		this.format=format;
	}

	 
	 public boolean canConvert(Class arg0) {

	  return Date.class == arg0;
	 }
	 
	 //对象转xml时使用
	 public void marshal(Object value, HierarchicalStreamWriter writer,
	   MarshallingContext arg2) {

		 Date date = (Date) value;
		 SimpleDateFormat formatter = new SimpleDateFormat(format);

		  writer.setValue(formatter.format(date));
	 }
	 //xml转对象时使用
	 public Object unmarshal(HierarchicalStreamReader reader,
	   UnmarshallingContext arg1) {
		 	Date date=new Date();
		 	String value=reader.getValue();
		 	if(value==null||value.trim().equals("")){
		 		 try {
					 date=DateTool.getDate("1800-01-01");
				} catch (Exception e1) {
				}
		 	}
		 	//适合于只有年的情况
		 	else if(value.length()==4){
		 		 try {
					 date=DateTool.getDate(value+"-01-01");
				} catch (Exception e1) {
				}
		 	}
		 	//适合于只有年、月的情况
		 	else if(value.length()==7){
		 		 try {
					 date=DateTool.getDate(value+"-01");
				} catch (Exception e1) {
				}
		 	}
		 	//适合于只有月、日的情况
		 	else if(value.length()==5){
		 		 try {
					 date=DateTool.getDate("1800-"+value);
				} catch (Exception e1) {
				}
		 	}
		 	else{
		        GregorianCalendar calendar = new GregorianCalendar(); 
		        SimpleDateFormat dateFm = new SimpleDateFormat(format); //格式化当前系统日期
		        try {
		                calendar.setTime(dateFm.parse(value));
		        } catch (ParseException e) {
		                throw new ConversionException(e.getMessage(), e);
		        } 
		        date=calendar.getTime();
		 	}
	        return date;

	 }
	 public static void main(String[] args) {
	}


}
